package com.lyf.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lyf.constant.MessageConstant;
import com.lyf.constant.StatusConstant;
import com.lyf.dto.DishDTO;
import com.lyf.dto.DishPageQueryDTO;
import com.lyf.exception.DeletionNotAllowedException;
import com.lyf.mapper.admin.DishFlavorMapper;
import com.lyf.mapper.admin.DishMapper;
import com.lyf.mapper.admin.SetmealDishMapper;
import com.lyf.pojo.Dish;
import com.lyf.pojo.DishFlavor;
import com.lyf.result.PageResult;
import com.lyf.service.DishService;
import com.lyf.utils.AliOssUtils;
import com.lyf.vo.DishItemVO;
import com.lyf.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private AliOssUtils aliOssUtils;

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> dishes = dishMapper.pageQuery(dishPageQueryDTO);

        PageResult pageResult = PageResult.builder()
                .total(dishes.getTotal())
                .records(dishes.getResult())
                .build();
        return pageResult;
    }

    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO = dishMapper.selectById(id);
        List<DishFlavor> flavors= dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 通过AOP 自动填充功能，更新时间、更新人
        dishMapper.insert(dish);
        Long dishId = dish.getId();
                // 插入菜品口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0){
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 修改菜品及其口味数据
     * @param dishDTO
     */

    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        Long dishId = dish.getId();
        // 新的菜品口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();

        // 更新菜品数据
        dishMapper.update(dish);

        // 删除已有菜品口味数据
        dishFlavorMapper.deleteByDishId(dishId);
        // 更新菜品口味数据
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        List<Dish> dishes = dishMapper.selectByIds(ids);
        for (Dish dish : dishes) {
            Long dishId = dish.getId();
            // 起售中的菜品不能删除
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 有关联套餐的菜品不能删除
        List<Long> setmealIds = setmealDishMapper.selectSetmealIdByDishIds(ids);
        if (setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品
        dishMapper.deleteBatch(ids);
        // 删除菜品口味
        dishFlavorMapper.deleteByDishIds(ids);
        // 删除图片
        for(Dish dish : dishes){
            try {
                aliOssUtils.deleteFile(dish.getImage());
            }catch (Exception e){
                System.err.println("图片删除失败: " + dish.getImage());
            }
        }
    }

    /**
     * 菜品起售停售
     * @param dish
     */
    @Override
    public void startOrStop(Dish dish) {
        dishMapper.update(dish);
    }

    /**
     * 根据菜品分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Long categoryId) {
        List<DishVO> dishes = dishMapper.list(categoryId);
        for (DishVO dishVO : dishes){
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(dishVO.getId());
            dishVO.setFlavors(flavors);
        }
        return dishes;
    }

    @Override
    public List<DishItemVO> getSetmealDIshItemsBySetmealId(Long id) {
        List<DishItemVO> list = dishMapper.getSetmealDIshItemsBySetmealId(id);
        return list;
    }
}
